package com.csoa.community.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.csoa.community.R;
import com.csoa.community.bean.AttachBean;
import com.csoa.community.bean.GongZuoModel;
import com.csoa.community.net.WcfAsyncTask;
import com.csoa.community.requests.AbstractRequest;
import com.csoa.community.requests.ComDownAttachRequest;
import com.csoa.community.requests.GongZuoXQRequest;
import com.csoa.community.requests.TongzhiAttachRequest;
import com.csoa.community.services.UpgradeService;
import com.csoa.community.singletons.GlobalVars;
import com.csoa.community.utils.AndroidUtils;
import com.csoa.community.utils.StringUtils;
import com.csoa.community.widget.PullToRefreshBase.OnRefreshListener;
import com.csoa.community.widget.PullToRefreshScrollView;

public class GongZuoXQActivity extends BaseActivity implements OnClickListener {

	public static final String extra_tongzhi = "extra_tongzhi";
	public static final String extra_position = "extra_position";

	private static Map<String, GongZuoModel> contents;

	ProgressBar mProgress;
	TextView title;
	TextView time;
	TextView content;
	TextView zuozhe;

	int preCount = 0;
	GongZuoModel model;
	int position;
	private LinearLayout mTongzhiAttachTipLayout;
	private LinearLayout mTongzhiAttachLayout;
	private PullToRefreshScrollView mPullScroll;
	private ScrollView scroll;
	private LayoutInflater inflater;
	private View mScollerContentView;

	@Override
	public void initUI() {
		setContentView(R.layout.gongzuo_xq);
		mPullScroll = (PullToRefreshScrollView) this
				.findViewById(R.id.gongzuoScrollView);
		mPullScroll.setMode(PullToRefreshScrollView.MODE_PULL_DOWN_TO_REFRESH);
		mPullScroll.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				buildRequestGetGongZuo();
			}
		});
		scroll = mPullScroll.getRefreshableView();
		// scroll = (ScrollView) this.findViewById(R.id.gongzuoScrollView);
		inflater = LayoutInflater.from(this);
		mScollerContentView = inflater.inflate(R.layout.common_xq_scroller,
				null);
		scroll.addView(mScollerContentView);
		// 附件layout（包括附件的标题）
		mTongzhiAttachTipLayout = (LinearLayout) this
				.findViewById(R.id.tongzhiAttachTipLayout);

		// 附件layout
		mTongzhiAttachLayout = (LinearLayout) this
				.findViewById(R.id.tongzhiAttachLayout);

		this.findViewById(R.id.tzx_btn_pre).setOnClickListener(this);
		this.findViewById(R.id.tzx_btn_next).setOnClickListener(this);

		title = (TextView) this.findViewById(R.id.tzx_title);
		time = (TextView) this.findViewById(R.id.tzx_time);
		content = (TextView) this.findViewById(R.id.tzx_content);
		zuozhe = (TextView) this.findViewById(R.id.tzx_zuozhe);
		mProgress = (ProgressBar) this.findViewById(R.id.tzx_progress);

		content.setMovementMethod(ScrollingMovementMethod.getInstance());

		super.initUI();
	}

	@Override
	public void initData() {
		model = (GongZuoModel) getIntent().getSerializableExtra(extra_tongzhi);
		position = getIntent().getIntExtra(extra_position, 0);

		if (contents == null) {
			contents = new HashMap<String, GongZuoModel>();
		}

		title.setText(model.name);
		time.setText(model.time);

		if (!contents.containsKey(model.id)) {
			buildRequestGetGongZuo();
		} else {
			initCenterUI(true);
			model = contents.get(model.id);
			initText();
		}
		super.initData();
	}

	@Override
	public void onClick(View v) {
		scroll.scrollTo(0, 0);
		switch (v.getId()) {
		case R.id.tzx_btn_pre:
			if (position == 0) {
				showToast("没有更多动态了.");
				return;
			}
			stopTask();
			model = GongZuoActivity.data.get(position - 1);
			title.setText(model.name);
			time.setText(model.time);
			zuozhe.setText("");
			position--;
			if (contents.containsKey(model.id)) {
				initCenterUI(true);
				model = contents.get(model.id);
				initText();
			} else {
				buildRequestGetGongZuo();
			}
			content.scrollTo(0, 0);
			break;
		case R.id.tzx_btn_next:
			if (position == (GongZuoActivity.data.size() - 1)) {
				showToast("没有更多动态了.");
				return;
			}
			stopTask();
			model = GongZuoActivity.data.get(position + 1);
			title.setText(model.name);
			time.setText(model.time);
			zuozhe.setText("");
			position++;
			if (contents.containsKey(model.id)) {
				initCenterUI(true);
				model = contents.get(model.id);
				initText();
			} else {
				buildRequestGetGongZuo();
			}
			content.scrollTo(0, 0);
			break;
		default:
			break;
		}
	}

	public void initText() {
		biaoshiRead();
		title.setText(model.name);
		time.setText(model.time);
		if (StringUtils.isNotEmpty(model.zuozhe)) {
			zuozhe.setText(model.zuozhe);
		}
		content.setText("");
		if (StringUtils.isNotEmpty(model.content)) {
			content.setText(Html.fromHtml(model.content));
		} else {
			content.setText("暂无正文信息");
		}
		setDataToAttachView(model.attachs);
	}

	protected void buildRequestGetGongZuo() {
		mTongzhiAttachTipLayout.setVisibility(View.GONE);
		mPullScroll.showHeadView();
		initCenterUI(false);
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("DocumentID", model.id));
		netRequestGetGongZuo(new GongZuoXQRequest(params));
	}

	WcfAsyncTask task;

	private void netRequestGetGongZuo(AbstractRequest request) {
		stopTask();
		task = new WcfAsyncTask(this, new OnUICallback() {
			@Override
			public void onGetResult(AbstractRequest request) {
				initCenterUI(true);
				mPullScroll.onRefreshComplete();
				GongZuoXQRequest mRq = (GongZuoXQRequest) request;
				if (mRq.model != null) {
					contents.remove(model.id);
					contents.put(model.id, mRq.model);
					model = mRq.model;
					initText();
					buildAttachRequest(model.id);
				}
			}

			@Override
			public void onCancel() {
				initCenterUI(true);
				mPullScroll.onRefreshComplete();
			}

			@Override
			public void onProgress(int progress, String msg) {
				GongZuoXQActivity.this.showToast(msg);
			}
		});
		task.execute(request);
	}

	private void stopTask() {
		if (task != null) {
			task.cancel(true);
		}
	}
	
	/**
	 * 标识已读
	 */
	protected void biaoshiRead() {
		if(position < GongZuoActivity.data.size() && GongZuoActivity.mAdapter!= null) {
			GongZuoActivity.data.remove(position);
			model.isRead = true;
			GongZuoActivity.data.add(position,model);
			GongZuoActivity.mAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * 下载附件构建Request
	 * 
	 * @param request
	 */
	protected void buildAttachRequest(String DocumentID) {
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("DocumentID", DocumentID));
		netRequestAttach(new TongzhiAttachRequest(params));
	}

	/**
	 * 下载附件
	 * 
	 * @param request
	 */
	private void netRequestAttach(TongzhiAttachRequest request) {
		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onCancel() {

			}

			@Override
			public void onProgress(int progress, String msg) {
				GongZuoXQActivity.this.showToast(msg);
			}

			@Override
			public void onGetResult(AbstractRequest result) {
				TongzhiAttachRequest attachRequest = (TongzhiAttachRequest) result;
				if (attachRequest.mAttachs != null) {
					model.attachs = attachRequest.mAttachs;
					setDataToAttachView(attachRequest.mAttachs);
				}
			}
		}).execute(request);
	}

	/**
	 * 附件下载完毕之后显示在界面中
	 * 
	 * @param mAttachs
	 */
	protected void setDataToAttachView(List<AttachBean> mAttachs) {
		mPullScroll.onRefreshComplete();
		mTongzhiAttachLayout.removeAllViews();
		if (mAttachs == null || mAttachs.size() == 0) {
			mTongzhiAttachTipLayout.setVisibility(View.GONE);
			return;
		}
		mTongzhiAttachTipLayout.setVisibility(View.VISIBLE);

		for (int i = 0; i < mAttachs.size(); i++) {
			final AttachBean attach = mAttachs.get(i);
			TextView text = new TextView(this);
			text.setText("附件" + (i + 1) + ":" + attach.FileName);
			text.setTextSize(18);
			text.setTextColor(this.getResources().getColor(R.color.attach));
			text.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					boolean isAttachExists = GlobalVars.getInst()
							.isAttachExists(getApplicationContext(),
									attach.FileName);

					if (!isAttachExists) {

						if (!AndroidUtils.isNetworkValidate(GongZuoXQActivity.this)) {
							GongZuoXQActivity.this.showToast("无法检测到网络,检查网络是否开启");
							return;
						}
						buildDownLoadAttachRequest(attach);
					}


				}
			});
			mTongzhiAttachLayout.addView(text);
		}
	}

	protected void buildDownLoadAttachRequest(AttachBean attach) {
		showProgress();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("AttachID", attach.AttachID));
		params.add(new BasicNameValuePair("FileType", attach.FileExtend));
		netRequestDownAttach(new ComDownAttachRequest(params), attach);
	}

	private void netRequestDownAttach(ComDownAttachRequest request,
			final AttachBean attach) {

		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				ComDownAttachRequest downAttachRequest = (ComDownAttachRequest) request;
				if (!StringUtils.isEmpty(downAttachRequest.success)
						&& "1".equals(downAttachRequest.success)) {

					GongZuoXQActivity.this
							.showToast("附件后台下载中...,下载完成自动存入CSOA目录中");
					startService(attach);
				} else {
					GongZuoXQActivity.this.showToast("获取附件失败,附件可能已经删除");
				}
			}

			@Override
			public void onCancel() {
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				GongZuoXQActivity.this.showToast(msg);
			}
		}).execute(request);

	}

	private void startService(AttachBean attach) {

		Intent intent = new Intent();
		intent.setClass(this, UpgradeService.class);
		intent.putExtra("AttachID", attach.AttachID);
		intent.putExtra("FileExtend", attach.FileExtend);
		intent.putExtra("FileName", attach.FileName);
		this.startService(intent);
	}

	private void initCenterUI(boolean isShowList) {
		if (isShowList) {
			if (content.getVisibility() != View.VISIBLE) {
				content.setVisibility(View.VISIBLE);
			}
			if (mProgress.getVisibility() != View.INVISIBLE) {
				mProgress.setVisibility(View.INVISIBLE);
			}
		} else {
			if (content.getVisibility() != View.INVISIBLE) {
				content.setVisibility(View.INVISIBLE);
			}
			if (mProgress.getVisibility() != View.VISIBLE) {
				mProgress.setVisibility(View.VISIBLE);
			}
		}
	}

}
